package com.bai.Controller;

import cn.hutool.Hutool;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.RandomUtil;
import com.bai.Constant.LoginConst;
import com.bai.Mapper.AdminMapper;
import com.bai.Pojo.Admin;
import com.bai.Service.AdminService;
import com.bai.Utils.DtoResultUtil;
import com.bai.dto.PageLimitDto;
import com.bai.dto.PublicResponseBody;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;


/**
 * @title: adminController
 * @Author BaiSc
 * @Date: 2021/6/5 16:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
     private AdminService adminService;
    @Autowired
    private AdminMapper mapper;
    //登录
    @PostMapping("/login")
    public PublicResponseBody login(@Param("username")String username,@Param("password")String password,HttpServletResponse response){
        //获得当前用户到登录对象，现在状态为未认证
        Subject subject= SecurityUtils.getSubject();
        Admin admin = mapper.findAdminByUsername(username);
        String newPwd=new SimpleHash("MD5",password,admin.getSalt(),1024).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(username, newPwd);
        if(!subject.isAuthenticated()){
            subject.login(token);
            Cookie cookie=new Cookie("username",username);
            cookie.setPath("/Final_ssm2");
            cookie.setMaxAge(-1);
            response.addCookie(cookie);
            System.out.println(token.hashCode());
            token.setRememberMe(true);
        }else{
            return DtoResultUtil.resultError();
        }
        return DtoResultUtil.resultSuccess();
    }

    //查询所有管理员
    @RequiresRoles(value={"admin"},logical= Logical.OR)
    @GetMapping("/Admin_table")
    public PageLimitDto QueryAllAdmin(Integer offset,Integer limit){
        PageLimitDto result = adminService.queryAllAdmin(offset,limit);
        return result;
    }
    //删除
    @RequiresRoles(value={"admin"},logical= Logical.OR)
    @GetMapping("/delete")
    public PublicResponseBody delete(Integer id){
        if (id!=null){
            PublicResponseBody result = adminService.deleteAdmin(id);
            if (result==null){
                return DtoResultUtil.resultError();
            }
            return result;
        }else {
            return DtoResultUtil.resultParamError();
        }
    }

    //添加
    @RequiresRoles(value={"admin"},logical= Logical.OR)
    @GetMapping("/add")
    public PublicResponseBody add(Admin admin){
        String s = RandomUtil.randomString(11);
        ByteSource salt=ByteSource.Util.bytes(s);
        String newPwd=new SimpleHash("MD5",admin.getPassword(),salt,1024).toString();
//        new Md5Hash(loginName + password + salt).toHex()
        admin.setPassword(newPwd);
        admin.setSalt(s);
        PublicResponseBody addAdmin = adminService.addAdmin(admin);
        if (addAdmin!=null){
            if (addAdmin==null){
                return DtoResultUtil.resultError();
            }
            return addAdmin;
        }else {
            return DtoResultUtil.resultParamError();
        }
    }

    //修改
    @RequiresRoles(value={"admin"},logical= Logical.OR)

    @PostMapping("/edit")
    public PublicResponseBody edit(Admin admin){
        PublicResponseBody addAdmin = adminService.editAdmin(admin);
        if (addAdmin!=null){
            if (addAdmin==null){
                return DtoResultUtil.resultError();
            }
            return addAdmin;
        }else {
            return DtoResultUtil.resultParamError();
        }
    }

    //查看
    @GetMapping("/getDetail")
    public PublicResponseBody getDetail(Integer id){
        if (id!=null){
            PublicResponseBody addAdmin = adminService.getAdmin(id);
            if (addAdmin!=null){
                if (addAdmin==null){
                    return DtoResultUtil.resultError();
                }
                return addAdmin;
            }else {
                return DtoResultUtil.resultParamError();
            }
        }
        return DtoResultUtil.resultParamError();
    }
    @GetMapping("/logout")
    public PublicResponseBody logout(){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return DtoResultUtil.resultSuccess();
    }


    /**
     * 生成验证码
     * @param response
     */
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        // 定义图片的显示大小
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 4);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
